<?php


namespace app\api\controller;


use app\BaseController;
use Composer\Autoload\ClassLoader;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\console\command\VendorPublish;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;

class
Smoke extends AuthBase
{
    protected $noLogin = ['index','phone_code'];
    public function category_index(){
        $model=Db::name('smoke_category')
            ->column('id,name');
        return $this->show(1,'success',$model);
    }
    public function brand_index(){
        $category_id=input('get.category_id',1);
        $model=Db::name('smoke_brand')
            ->order('hot desc')
            ->where('category_id',$category_id)
            ->column('id,name');
        return $this->show(1,'success',$model);
    }
    public function index(){
        $category_id=input('get.brand_id');
        $name=input('get.name');
        $where=[];
        if (!empty($name)){
            $where[]=[
                'name','like',"%$name%"
            ];
        }
        if (!empty($category_id)){
            $where[]=[
                'brand_id','=',$category_id
            ];
        }
        if (!$category_id&&!$name){
            return show(1,'success',[]);
        }
        $model=Db::name('smoke')
            ->where($where)
            ->order('hot desc')
            ->column('id,name,hot,img,price,tar,nicotine,co');
        if ($category_id==1){
            $model[0]['hot']=0;
        }
        return $this->show(1,'success',$model);
    }
    public function user_index(){
        $model=Db::name('user_smoke')
            ->where('u.user_id',$this->userId)
            ->alias('u')
            ->leftJoin('smoke s','s.id=u.smoke_id')
            ->order('u.type','asc')
            ->order('u.num','desc')
            ->column('u.id,s.id as smoke_id,s.img,s.name,u.price,u.num,u.type');
        return $this->show(1,'success',$model);
    }
    //设置为默认香烟
    public function edit_smoke_default(){
        $id=input('get.id');
        Db::startTrans();
        try {
            Db::name('user_smoke')
                ->where('user_id',$this->userId)
                ->update(['type'=>2]);
            Db::name('user_smoke')->where(['id'=>$id,'user_id'=>$this->userId])->update(['type'=>1]);
            Db::commit();
            return show(1, '保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            return show(0, $e->getMessage());
        }
    }
    public function detail(){
        $id=input('get.id');
        $model=Db::name('smoke')
            ->where('id',$id)
            ->find();
        return $this->show(1,'success',$model);
    }
}